package com.yoomiito.app.ui.my.remain.withdraw

import android.content.ContentValues
import android.content.Intent
import android.net.Uri
import android.os.Environment
import android.provider.MediaStore
import android.text.TextUtils
import android.util.Log
import cn.droidlover.xdroidmvp.net.ApiException
import cn.droidlover.xdroidmvp.net.ApiSubscriber
import cn.droidlover.xdroidmvp.net.BaseModel
import cn.droidlover.xdroidmvp.net.XApi
import com.yoomiito.app.base.AppConfig
import com.yoomiito.app.base.BaseActPresenter
import com.yoomiito.app.model.my.ApplyInfo
import com.yoomiito.app.net.UploadFileManager
import com.yoomiito.app.net.UploadFileManager.UploadFileCallBack
import com.yoomiito.app.net.YmApi
import com.yoomiito.app.utils.NetworkUtils
import com.yoomiito.app.utils.YMToast
import java.io.File
import java.io.IOException
import java.text.SimpleDateFormat
import java.util.Date

class AddWithdrawPresenter(appConfig: AppConfig) : BaseActPresenter<AddWithdrawActivity>(appConfig) {


    private var mCurrentPhotoPath: String? = null

    fun getmCurrentPhotoPath(): String? {
        return mCurrentPhotoPath
    }

    fun setmCurrentPhotoPath(mCurrentPhotoPath: String?) {
        this.mCurrentPhotoPath = mCurrentPhotoPath
    }

    fun accountInsert(applyInfo: ApplyInfo) {
        if (NetworkUtils.checkNetPermission(v)) {
            return
        }
        YmApi.getYmService()
                .accountInsert(applyInfo)
                .compose<BaseModel<*>>(v.bindToLifecycle<BaseModel<*>>())
                .compose<BaseModel<*>>(XApi.getApiTransformerNoData<BaseModel<*>>())
                .compose<BaseModel<*>>(XApi.getScheduler<BaseModel<*>>())
                .subscribe(object : ApiSubscriber<BaseModel<*>?>(handleException()) {
                    override fun onSuccess(t: BaseModel<*>?) {
                        YMToast.showText("保存成功")
                        v.finish()
                    }

                    override fun onFail(error: ApiException) {
                        v.dismissLoading()
                    }
                })

    }


    fun accountDelete(id: String) {
        if (NetworkUtils.checkNetPermission(v)) {
            return
        }
        YmApi.getYmService()
                .accountDelete(id)
                .compose<BaseModel<*>>(v.bindToLifecycle<BaseModel<*>>())
                .compose<BaseModel<*>>(XApi.getApiTransformerNoData<BaseModel<*>>())
                .compose<BaseModel<*>>(XApi.getScheduler<BaseModel<*>>())
                .subscribe(object : ApiSubscriber<BaseModel<*>?>(handleException()) {
                    override fun onSuccess(t: BaseModel<*>?) {
                        YMToast.showText("删除成功")
                        v.finish()
                    }

                    override fun onFail(error: ApiException) {
                        v.dismissLoading()
                    }
                })

    }

    fun uploadPhotos( path: String?) {
        if (!TextUtils.isEmpty(path)) {
            UploadFileManager.uploadFile(path, "0", object : UploadFileCallBack {
                override fun uploadSucc(filename: String, key: String) {
                    Log.e("lin", "imageUrl-->$filename")
                    mCurrentPhotoPath = filename;
                }

                override fun uploadFail(code: Int, key: String) {
                    YMToast.showText("上传失败")
                }
            })
        }
    }

    fun takeCamera(num: Int) {
        val takePictureIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
        // Ensure that there's a camera activity to handle the intent
        if (takePictureIntent.resolveActivity(v.packageManager) != null) {
            // Create the File where the photo should go
            var photoFile: File? = null
            photoFile = createImageFile()
            // Continue only if the File was successfully created
            if (photoFile != null) {
//                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
//                        Uri.fromFile(photoFile));
                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
                        getImageContentUri(photoFile))
            }
        }
        v.startActivityForResult(takePictureIntent, num) //跳转界面传回拍照所得数据
    }

    private fun createImageFile(): File? {
        val storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM)
        var image: File? = null
        try {
            image = File.createTempFile(
                    generateFileName(),  /* prefix */
                    ".jpg",  /* suffix */
                    storageDir /* directory */
            )
        } catch (e: IOException) {
            e.printStackTrace()
        }
        mCurrentPhotoPath = image!!.absolutePath
        return image
    }

    fun generateFileName(): String? {
        val timeStamp = SimpleDateFormat("yyyyMMdd_HHmmss").format(Date())
        return "JPEG_" + timeStamp + "_"
    }

    fun getImageContentUri(imageFile: File): Uri? {
        val filePath = imageFile.absolutePath
        val cursor = v.contentResolver.query(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI, arrayOf(MediaStore.Images.Media._ID),
                MediaStore.Images.Media.DATA + "=? ", arrayOf(filePath), null)
        return if (cursor != null && cursor.moveToFirst()) {
            val id = cursor.getInt(cursor
                    .getColumnIndex(MediaStore.MediaColumns._ID))
            val baseUri = Uri.parse("content://media/external/images/media")
            Uri.withAppendedPath(baseUri, "" + id)
        } else {
            if (imageFile.exists()) {
                val values = ContentValues()
                values.put(MediaStore.Images.Media.DATA, filePath)
                v.contentResolver.insert(
                        MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values)
            } else {
                null
            }
        }
    }


    fun getIsAgent() {
        if (NetworkUtils.checkNetPermission(v)) {
            return
        }
//        YmApi.getYmService()
//                .moneyAgent
//                .compose(v.bindToLifecycle())
//                .compose(XApi.getApiTransformerData())
//                .compose(XApi.getScheduler())
//                .subscribe(object : ApiSubscriber<MyRemainMoneyInfo>() {
//                    override fun onSuccess(data: MyRemainMoneyInfo) {
//                        if (hasV())
//                            v.setIsAngent(data)
//                    }
//
//                    override fun onFail(error: ApiException) {
//                        YMToast.showText(error.msg)
//                    }
//                })
    }




}
